#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main(int argc , char* argv[]) {

	if(argc != 4) cout << "Error" << endl;

	ifstream file1;
	ifstream file2;
	ofstream out;

	file1.open(argv[1]);
	file2.open(argv[2]);
	out.open(argv[3]);

	if( !file1.is_open() ) cout << "Error: file1";
	if( !file2.is_open() ) cout << "Error: file2";
	if( !out.is_open() ) cout << "Error: out";

	string line1 = "" , line2 = "";
	string ngram1 , ngram2;
	string ngram;

	char* tok , *l;
	int freq , freq1 , freq2;
	int i = 0;
	int cmp;

	while( !file1.eof() && !file2.eof() ) {
		if(line1 == "") {
			getline(file1 , line1);
			if(line1 == "") break;
			l = new char[line1.length() + 1];
			strcpy( l , line1.c_str() );
			tok = strtok(l , "\t");
			ngram1 = tok;
			tok = strtok(NULL , "\n");
			freq1 = atoi(tok);
			delete [] l;
		}

		if(line2 == "") {
			getline(file2 , line2);
			if(line2 == "") break;
			l = new char[line2.length() + 1];
			strcpy( l , line2.c_str() );
			tok = strtok(l , "\t");
			ngram2 = tok;
			tok = strtok(NULL , "\n");
			freq2 = atoi(tok);
			delete [] l;
		}

		cmp = ngram1.compare(ngram2);
		if(cmp < 0) {
			ngram = ngram1;
			freq = freq1;
			line1 = "";
		}
		else {
			ngram = ngram2;
			if(cmp == 0) {
				freq = freq1 + freq2;
				line1 = "";
			}
			else freq = freq2;
			line2 = "";
		}

		out << ngram << "\t" << freq << endl;

		i++;
		if(i % 100000 == 0) cout << i << endl;

	}

	//Copia el resto del archivo que todavia no se termino.
	if( !file1.eof() )
		do {
			getline(file1 , line1);
			if(line1 != "") out << line1 << endl;
		} while( !file1.eof() );
	else
		do {
			getline(file2 , line2);
			if(line2 != "") out << line2 << endl;
		} while( !file2.eof() );

	file1.close();
	file2.close();
	out.close();
}




